package ifmo.group5512.timer;

import java.io.*;
import java.net.Socket;

/**
 * Created with IntelliJ IDEA.
 * User: katerina
 * Date: 01.11.12
 * Time: 13:28
 * To change this template use File | Settings | File Templates.
 */
public class Communicator implements Runnable {

    private final Socket socket;

    public Communicator(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        InputStream is;
        OutputStream os;

        try {
            is = socket.getInputStream();
            os = socket.getOutputStream();
        } catch (IOException ex) {
            System.err.println("Unable to establish input or output connection.");
            return;
        }

        boolean flag = true;
        while (flag) {
            try {
                flag = interact(is, os);
            } catch (IOException ex) {
                System.err.println("Interaction error.");
                break;
            }
        }

        try {
            socket.close();
        } catch (IOException ex) {
            System.err.println("Unable to close socket.");
        }
    }

    private boolean interact(InputStream is, OutputStream os) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        String input = reader.readLine();
        if (input == null || input.equals("close")) {
            return false;
        }

        String output = Commander.processCommand(input);

        System.out.println("Input: " + input + "; Output: " + output);

        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os));
        writer.write(output + "\n");
        writer.flush();
        return true;
    }
}
